//本js中调用日期的function都在common/js/dateUtil.js中
SdsMsta = {
    analysisDicChart : null,
    analysisDicTable : null
};

$(function () {
    /*//日期范围
    $('#dateRange').combobox({
        data:[
              {value:"0",text:"上个周"},
              {value:"1",text:"上个月"},
              {value:"2",text:"最近一月"},
              {value:"3",text:"最近三月"},
              {value:"4",text:"最近一年"},
              {value:"5",text:"自定义"}
              ],
        valueField:'value',
        textField:'text',
        onSelect:AnalysisCase.dateRangeChange,
        onLoadSuccess:function () {
            $(this).combobox("setValue", "1");
        }
    });*/

    //统计粒度
    /*$('#analysisGrain').combobox({
        data:[
              {value:"0",text:"天"},
              {value:"1",text:"周"},
              {value:"2",text:"月"},
              {value:"3",text:"年"}
              ],
        valueField:'value',
        textField:'text',
        onLoadSuccess:function () {
            $(this).combobox("setValue", "2");
        }
    });*/
    //科室
    $('#depart').combobox({
        data:$.parseJSON($("#departMap").val()),
        valueField:'value',
        textField:'text'
        //onSelect:ManageIndex.departChange
    });
    //院区
    $('#office').combobox({
        data:$.parseJSON($("#officeMap").val()),
        valueField:'value',
        textField:'text',
        onSelect:SdsMsta.officeChange,
        onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
            var val = $(this).combobox("getData");
            if(val.length==2){//如果就一个院区 加上全部=2
                $(this).combobox("setValue", val[1].value);
                SdsMsta.officeChange(val[1]);
                $("#oneOffice").val("yes");
            }else{
                $(this).combobox("setValue", "");
                $("#oneOffice").val("no");
            }
        }
    });
   /* $('#office').combobox({
        data:[{value:"",text:"全部"}],
        valueField:'value',
        textField:'text'
        //onSelect:ManageIndex.departChange
    });*/
    //病种
    $('#qcEntity').combobox({
        data:$.parseJSON($("#entityMap").val()),
        valueField:'value',
        textField:'text'
        //onSelect:ManageIndex.departChange
    });


    //获取上个月日期
    /*var lastMonths = getLastMonthStartDate();//YYYY-MM-DD
    var lastYearMonth = lastMonths.substring(0, 7);
    $("#startDate").val(lastYearMonth);
    $("#endDate").val(lastYearMonth);
    laydate.render({
        elem : '#dateRange',
        type : 'month',
        theme: '#afcede',
        range : true,
        value: lastYearMonth+' - '+lastYearMonth,
        done: function(value, start, end){
            var startMonth = start.month<10?"0"+start.month:start.month;
            var endMonth = end.month<10?"0"+end.month:end.month;
            var startDate = start.year+"-"+startMonth;
            var endDate = end.year+"-"+endMonth;
            $("#startDate").val(startDate);
            $("#endDate").val(endDate);
        }
    });*/
    /*$('#startDate').datebox('setValue',getMonthStartDate());
    $('#endDate').datebox('setValue',getMonthEndDate());*/
    $('#startDate').datebox('setValue',$("#startDateV").val());
    $('#endDate').datebox('setValue',$("#endDateV").val());
    $('#qcEntity').combobox('setValue',$("#qcEntityV").val());
    $('#office').combobox('setValue',$("#officeV").val());
    $('#depart').combobox('setValue',$("#departV").val());

    //查询加载表格的数据
    SdsMsta.initChartTable();


});
/**
 * //根据父级机构 查询子机构
 */
SdsMsta.officeChange = function(that){
    var ajax = new $ax("/sds/common/deptListByHospId", function(data){
        var data = $.parseJSON(data.message);
        $('#depart').combobox({
            data:data,
            valueField:'value',
            textField:'text',
            onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
                $(this).combobox("setValue", "");
            }
        });
    },function(data){
        layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
    });
    ajax.set({"hospID":that.value,"id":"depart"});
    ajax.start();
}
/**
 * 查询图和表数据
 */
SdsMsta.initChartTable = function(){
    var params = {};
    var ajax = new $ax("/api/selectSdsMstaDepart", function (data) {
        SdsMsta.drawChart(data.chartDatas);
        $('#analysisTable').bootstrapTable("destroy");//先销毁原来的表格
        SdsMsta.drawTable(data.tableDates);
        var key = $("#key").val();
        if ("upLoc" == key){
            $('#analysisTable').bootstrapTable('showColumn', 'locDesc');
            //合并单元格
            mergeCells(data.tableDates, "locDesc", 1, $('#analysisTable'));
        } else if ("upEntity" == key){
            $('#analysisTable').bootstrapTable('hideColumn', 'locDesc');
        }
        $("#analysisTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
            $(this).attr("title",$(this).text());
        });
    }, function (data) {
    });

    if ($('#startDate').datebox('getValue') != ""){
        params.startDate = $('#startDate').datebox('getValue')+" 00:00:00";//开始日期
        params.endDate = $('#endDate').datebox('getValue')+" 23:59:59";//开始日期
    } else {
        params.startDate = "";//开始日期
        params.endDate = "";//开始日期
    }
    params.office = $("#office").combobox("getValue");
    params.depart = $("#depart").combobox("getValue");
    params.qcEntity = $("#qcEntity").combobox("getValue");
    params.key = $("#key").val();
    ajax.set(params);
    ajax.start();
};

/**
 * 根据数据画图
 */
SdsMsta.drawChart = function(chartDatas){
    echarts.init($("#analysisChart")[0]).dispose();
    var qcEntity = $("#qcEntity").combobox("getText");
    var lines = [
        {desc:qcEntity+'上报率',data:[],code:'confirmRate'}
    ];
    /*var chartParams = {
        backgroundColor : '#f2f2f2',//背景颜色
        isHorizontal : false,
        yAxisName : '单位:%',//y轴单位
        formatterFunc : function(params){
            var backStr = "";
            var relVal = params[0].name;
            backStr += relVal + "<br>";
            for (var i = 0;i < params.length; i++) {
                backStr += params[i].marker+params[i].seriesName + "：" +params[i].value+ "%<br>";
            }
            return backStr;
        },
        titleShow:false,
        isDataZoom:false,//是否显示缩放
        legendShow : true,
        legendPosition : 'top',
        gridLeft:"20px",
        gridRight:"10px",
        gridTop:"30px",
        gridBottom:"50px",
        rotate:60,//x轴数据偏移角度
        showLabel : true,
        legend:{
            show : false
        }
    };*/
    var chartParams = {
        //backgroundColor : '#f2f2f2',
        isHorizontal : false,
        legendShow : false,
        showLabel : true,
        yAxisName : '%',//y轴单位
        legend:{
            show : false
        },
        isDataZoom:false,//是否显示缩放
        titleLeft:'center',//标题位置
        xAxisInterval:0,//坐标轴刻度标签的显示间隔，在类目轴中有效。默认会采用标签不重叠的策略间隔显示标签。可以设置成 0 强制显示所有标签
        rotate:50,//x轴数据偏移角度
        grid:{
            containLabel: true, //注意加上，否则axisLabel有可能显示会不全
            top:"35px",
            left:"20px",
            right:"20px",
            bottom:"50px"
        },
        label:{
            show:true,
            position:'top'
        }
    };
    /*lineChartVte($("#analysisChart"), lines, chartDatas,null,null,chartParams);*/
    barChartVte($("#analysisChart"), lines, chartDatas["confirmRate"], qcEntity+'上报率',null,chartParams);
};
/**
 * 根据数据画表
 */
SdsMsta.drawTable = function(tableDates){
    this.$table =
        $('#analysisTable').bootstrapTable({
            data:tableDates,

            striped: false,//是否显示行间隔色
            pagination: false,//是否显示分页
            showFooter: true,
            //paginationLoop: false,
            //pageSize : 5,//用于设置每页初始显示的条数
            //pageList :[4],
            //sidePagination: 'server',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
            sortName: "locDesc",
            sortOrder: 'desc',// desc  asc
            maintainSelected: true,//设为true 为选中的状态
            cache: false,
            search:false, //搜索框
            columns: SdsMsta.columns,
            onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
                //$(".th-inner").css("font-weight","700");//表头字体加粗
                $("#analysisTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
                    $(this).attr("title",$(this).text());
                });
            },
            onLoadSuccess: function () {//当所有数据被加载时触发处理函数
                /*mergeCells(tableDates,'locDesc',1,$('#analysisTable'));*/
                console.log("2021.7.6")
            }
        });
};

var data = $('#analysisTable').bootstrapTable('getData', true);
//合并单元格
mergeCells(data, "locDesc", 1, $('#analysisTable'));
$("#analysisTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
    $(this).attr("title",$(this).text());
});

/**
 * 导出表格数据
 */
SdsMsta.exportTable = function() {
    //AnalysisCase.analysisTableHead();
    //var getFirstChild = .("fixed-table-footer")[0].childNodes[0];
    //var test1 = $("fixed-table-footer :first-child");
    $("#analysisTableHead,#analysisTable,.fixed-table-footer>table").tableExport(
        {
            type : 'xlsx',
            escape : 'false'
        },$('#startDate').val()+"-"+$('#endDate').val()+'出院患者全院分析'
    )

};
//$('#startDate').datebox('getValue')+"-"+$('#endDate').datebox('getValue')
/**
 * 添加表格查询条件
 */
SdsMsta.analysisTableHead=function(){
    var params = {};
    params.office = $HUI.combobox('#office').getText();//院区
    params.depart = $HUI.combobox('#depart').getText();//部门
    params.dateRange = $('#dateRange').val();//日期范围
    params.qcEntity = $HUI.combobox('#qcEntity').getText();//病种
    var tableHead=document.getElementById("analysisTableHead");
    var tr="<tr><td>院区：</td>"+"<td>"+params.office+"</td>"+"<td>科室：</td>"+"<td>"+params.depart+"</td>"+"<td>日期范围：</td>"+"<td>"+params.dateRange+"</td>"+"<td>病种：</td>"+"<td>"+params.qcEntity+"</td>"+"</tr>";
    tableHead.innerHTML=tr;
};

/**
 * 表格表头
 */
SdsMsta.columns = [
    {title: '科室名称', field: 'locDesc', align: 'center', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return "";
        }
    },
    {title: '单病种名称', field: 'entityDesc', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return "总计";
        }
    },
    {title: '符合例数', field: 'consistentNum', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"consistentNum");
        }
    },
    {title: '已上报', field: 'reported', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"reported");
        }
    },
    {title: '上报率', field: 'reportedRate', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            //return value+"&nbsp;&nbsp;("+MathMethod(row.reported,row.consistentNum)+")";
            return MathMethod(row.reported,row.consistentNum)+"%&nbsp;&nbsp;("+value+")";
        },
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"reportedRate");
        }
    },
    {title: '次均住院日', field: 'averageHosDays', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"averageHosDays");
        }
    },
    {title: '次均住院费用', field: 'averageHosCost', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"averageHosCost");
        }
    },
    {title: '死亡例数', field: 'deathNum', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"deathNum");
        }
    },
    {title: '病死率', field: 'deathNumRate', align: 'left', valign: 'middle', sortable: true,
        formatter:function(value,row,index){
            //return value+"&nbsp;&nbsp;("+MathMethod(row.deathNum,row.consistentNum)+")";
            return MathMethod(row.deathNum,row.consistentNum)+"%&nbsp;&nbsp;("+value+")";
        },
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"deathNumRate");
        }
    },
    {title: '平均耗材费', field: 'averageConsumCost', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"averageConsumCost");
        }
    },
    {title: '平均药费', field: 'averageMedeCost', align: 'left', valign: 'middle', sortable: true,
        footerFormatter:function(value){
            return SdsMsta.sumFieldValue(value,"averageMedeCost");
        }
    }

];
/**
 * 计算表格最后一列数据和
 */
SdsMsta.sumFieldValue = function(value,field){
    var disSum = 0;
    var count = 0;
    for(var i in value){
        count += value[i][field]*1000;
        disSum += value[i]["consistentNum"]*1000;
    }
    if(count==0){//如果是0返回空
        return ""
    }
    count = count/1000;
    disSum = disSum/1000;

    if(field=="reportedRate" || field=="deathNumRate"){
        var pre = (count/disSum * 100).toFixed(2);
        return pre+"%&nbsp;&nbsp;("+count+")";
    }

    return count;
};
/**
 * 查询按钮
 */
SdsMsta.search = function(){
    SdsMsta.initChartTable();
};
/**
 * 日期范围改变时调用
 */
SdsMsta.dateRangeChange = function(that){
    var rangeType = that.value;
    var startDate = "";
    var endDate = "";
    if(rangeType == 0){
        startDate = getLastWeekStartDate();
        endDate = getLastWeekEndDate();
    }else if(rangeType == 1){
        startDate = getLastMonthStartDate();
        endDate = getLastMonthEndDate();
    }else if(rangeType == 2){
        startDate = getOneMonthStartDate();
        endDate = formatDate(new Date());
    }else if(rangeType == 3){
        startDate = getThreeMonthStartDate();
        endDate = formatDate(new Date());
    }else if(rangeType == 4){
        startDate = getOneYearStartDate();
        endDate = formatDate(new Date());
    }else if(rangeType == 5){
        startDate = "";
        endDate = "";
    }

    //日期自定义启用 其他禁用
    if(rangeType == 5){
        $('#startDate').datebox('enable');
        $('#endDate').datebox('enable');
    }else{
        $('#startDate').datebox('disable');
        $('#endDate').datebox('disable');
    }
    //日期框赋值
    $('#startDate').datebox('setValue',startDate);
    $('#endDate').datebox('setValue',endDate);
}

/**
 * 计算比率
 */
function MathMethod(a,b){
    if(b==0){
        return "0";
    }
    var num = a/b;
    num = (num.toFixed(4)) * 100;  // 输出结果为 2.45
    var numStr = num.toString()
    var index = numStr.indexOf('.');
    if(index > -1){
        numStr = numStr.substring(0, index+3);
    }
    return numStr;
}

function mergeCells(data,fieldName,colspan,target){
    //声明一个map计算相同属性值在data对象出现的次数和
    var sortMap = {};
    for(var i = 0 ; i < data.length ; i++){
        for(var prop in data[i]){
            if(prop == fieldName){
                var key = data[i][prop]     //fieldName的value
                if(sortMap.hasOwnProperty(key)){
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
                break;
            }
        }
    }
    /*for(var prop in sortMap){
        console.log(prop,sortMap[prop])
    }*/
    //合并单元格
    var index = 0;
    for(var prop in sortMap){
        var count = sortMap[prop] * 1;
        $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
        index += count;
    }

}